package com.qifei.xmlg_backend.exception;

import com.qifei.xmlg_backend.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

@Slf4j
@RestControllerAdvice
public class  GlobalExceptionHandler {

    // 服务抛出的异常
    @ExceptionHandler(CustomException.class)
    public Result<String> handleBizException(CustomException ex) {
        // 直接使用枚举带的状态码
        return Result.error(ex.getCode(), ex.getMessage());
    }


    // 捕获所有运行时的异常
    @ExceptionHandler(RuntimeException.class)
    public Result<String> handleRuntimeException(RuntimeException ex) {
        ex.getStackTrace();
        log.error(ex.getMessage());
        return Result.error(500,"系统内部错误");
    }

    // 捕获参数锁定异常（如 @RequestBody 校验失败）
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleValidationException(MethodArgumentNotValidException ex){
        String errorMessage = ex.getBindingResult()
                .getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .findFirst()
                .orElse("参数校验失败");
        return Result.error(400,errorMessage);
    }

    // 处理404异常
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<String> handleNotFound(NoHandlerFoundException ex) {
        log.error("404错误: {}", ex.getRequestURL());
        return Result.error(404, "接口不存在");
    }

    // 处理405异常
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<String> handleMethodNotSupported(HttpRequestMethodNotSupportedException ex) {
        return Result.error(405, "不支持的请求方法");
    }

    // ✅ 处理权限不足异常
    @ExceptionHandler(AccessDeniedException.class)
    public Result<String> handleAccessDeniedException(AccessDeniedException ex) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        String username = (auth != null) ? auth.getName() : "未登录";
        String authorities = (auth != null) ? auth.getAuthorities().toString() : "无权限信息";

        log.warn("权限不足：用户 [{}] 权限 {}，访问被拒绝", username, authorities);

        return Result.error(403, "权限不足");
    }
}
